package com.explorati.interview.interview.Thread;

import java.util.concurrent.Semaphore;

public class PrintABCUsingSemaphore {

	private int times;
	Semaphore semaphoreA = new Semaphore(1);
	Semaphore semaphoreB = new Semaphore(0);
	Semaphore semaphoreC = new Semaphore(0);

	public PrintABCUsingSemaphore(int times) {
		this.times = times;
	}

	public void printA() {
		try {
			print("A", semaphoreA, semaphoreB);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public void printB() {
		try {
			print("B", semaphoreB, semaphoreC);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public void printC() {
		try {
			print("C", semaphoreC, semaphoreA);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	private void print(String str, Semaphore current, Semaphore next) throws InterruptedException {
		for (int i = 0; i < times; i++) {
			current.acquire();
			System.out.println(str);
			next.release();
		}
	}

	public static void main(String[] args) {
		PrintABCUsingLock printABCUsingLock = new PrintABCUsingLock(10);
		new Thread(() -> {
			printABCUsingLock.printA();
		}).start();
		new Thread(() -> {
			printABCUsingLock.printB();
		}).start();
		new Thread(() -> {
			printABCUsingLock.printC();
		}).start();
	}
}
